<template>
  <div class="promotions-page">
    <div class="page-header">
      <div class="header-left">
        <h2>促销活动</h2>
      </div>
      <div class="header-right">
        <a-button type="primary" @click="handleCreatePromotion">
          <template #icon><icon-plus /></template>
          创建活动
        </a-button>
      </div>
    </div>

    <!-- 活动数据概览 -->
    <a-row :gutter="16" class="data-overview">
      <a-col :span="6">
        <a-card class="overview-card">
          <statistic
            title="进行中活动"
            :value="statistics.activeCount"
            :value-style="{ color: '#2B5CE7' }"
          >
            <template #suffix>
              <icon-fire style="color: #ff7d00" />
            </template>
          </statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="overview-card">
          <statistic
            title="参与商品数"
            :value="statistics.productCount"
            :value-style="{ color: '#14C9C9' }"
          >
            <template #suffix>
              <icon-gift style="color: &quot;#14C9C9&quot;" />
            </template>
          </statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="overview-card">
          <statistic
            title="活动成交额"
            :value="statistics.salesAmount"
            :precision="2"
            prefix="¥"
            :value-style="{ color: '#FF7D00' }"
          />
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="overview-card">
          <statistic
            title="活动转化率"
            :value="statistics.conversionRate"
            suffix="%"
            :value-style="{ color: '#16CA45' }"
          />
        </a-card>
      </a-col>
    </a-row>

    <!-- 活动筛选 -->
    <a-card class="filter-card">
      <a-form :model="filterForm" layout="inline">
        <a-form-item field="status" label="活动状态">
          <a-radio-group v-model="filterForm.status" type="button">
            <a-radio value="all">全部</a-radio>
            <a-radio value="active">进行中</a-radio>
            <a-radio value="upcoming">未开始</a-radio>
            <a-radio value="ended">已结束</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item field="type" label="活动类型">
          <a-select
            v-model="filterForm.type"
            placeholder="请选择活动类型"
            style="width: 200px"
            allow-clear
          >
            <a-option value="discount">折扣优惠</a-option>
            <a-option value="fullReduction">满减优惠</a-option>
            <a-option value="directReduction">直降优惠</a-option>
            <a-option value="groupBuy">拼团优惠</a-option>
            <a-option value="secondHalf">第二件半价</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="dateRange" label="活动时间">
          <a-range-picker v-model="filterForm.dateRange" style="width: 260px" />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><icon-search /></template>
              搜索
            </a-button>
            <a-button @click="handleReset">
              <template #icon><icon-refresh /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 活动列表 -->
    <a-card class="list-card">
      <a-table
        :data="promotionList"
        :loading="loading"
        :pagination="pagination"
        @page-change="onPageChange"
      >
        <template #columns>
          <a-table-column title="活动信息" data-index="name">
            <template #title>
              <div class="column-title">
                活动信息
                <div class="sort-buttons">
                  <icon-up
                    :class="{
                      active:
                        sortKeys.field === 'name' &&
                        sortKeys.order === 'ascend',
                    }"
                    @click="handleSort('name', 'ascend')"
                  />
                  <icon-down
                    :class="{
                      active:
                        sortKeys.field === 'name' &&
                        sortKeys.order === 'descend',
                    }"
                    @click="handleSort('name', 'descend')"
                  />
                </div>
              </div>
            </template>
            <template #cell="{ record }">
              <div class="promotion-info">
                <a-image :src="record.image" :width="80" height="80" />
                <div class="info-content">
                  <h4>{{ record.name }}</h4>
                  <div class="tags">
                    <a-tag :color="getTypeColor(record.type)">{{
                      record.type
                    }}</a-tag>
                    <a-tag v-if="record.isRecommend" color="orange"
                      >店长推荐</a-tag
                    >
                  </div>
                  <div class="promotion-desc">{{ record.description }}</div>
                </div>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="优惠信息" align="center">
            <template #cell="{ record }">
              <div class="discount-info">
                <div class="discount-type">{{ record.discountType }}</div>
                <div class="discount-rules">
                  <template v-if="record.type === '满减优惠'">
                    <div v-for="(rule, index) in record.rules" :key="index">
                      满{{ rule.threshold }}减{{ rule.discount }}
                    </div>
                  </template>
                  <template v-else-if="record.type === '折扣优惠'">
                    {{ record.discount }}折
                  </template>
                  <template v-else>
                    {{ record.discountDesc }}
                  </template>
                </div>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="活动时间" align="center">
            <template #title>
              <div class="column-title">
                活动时间
                <div class="sort-buttons">
                  <icon-up
                    :class="{
                      active:
                        sortKeys.field === 'startTime' &&
                        sortKeys.order === 'ascend',
                    }"
                    @click="handleSort('startTime', 'ascend')"
                  />
                  <icon-down
                    :class="{
                      active:
                        sortKeys.field === 'startTime' &&
                        sortKeys.order === 'descend',
                    }"
                    @click="handleSort('startTime', 'descend')"
                  />
                </div>
              </div>
            </template>
            <template #cell="{ record }">
              <div class="time-info">
                <div>{{ record.startTime }}</div>
                <div>至</div>
                <div>{{ record.endTime }}</div>
                <a-tag :color="getStatusColor(record.status)" class="mt-2">
                  {{ record.status }}
                </a-tag>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="活动数据" align="center">
            <template #title>
              <div class="column-title">
                活动数据
                <div class="sort-buttons">
                  <icon-up
                    :class="{
                      active:
                        sortKeys.field === 'salesAmount' &&
                        sortKeys.order === 'ascend',
                    }"
                    @click="handleSort('salesAmount', 'ascend')"
                  />
                  <icon-down
                    :class="{
                      active:
                        sortKeys.field === 'salesAmount' &&
                        sortKeys.order === 'descend',
                    }"
                    @click="handleSort('salesAmount', 'descend')"
                  />
                </div>
              </div>
            </template>
            <template #cell="{ record }">
              <div class="promotion-stats">
                <div class="stat-item">
                  <span class="label">参与商品</span>
                  <span class="value">{{ record.productCount }}个</span>
                </div>
                <div class="stat-item">
                  <span class="label">活动成交</span>
                  <span class="value">¥{{ record.salesAmount }}</span>
                </div>
                <div class="stat-item">
                  <span class="label">转化率</span>
                  <span class="value">{{ record.conversionRate }}%</span>
                </div>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="操作" align="right" width="200">
            <template #cell="{ record }">
              <a-space>
                <a-button type="text" size="small" @click="handleEdit(record)"
                  >编辑</a-button
                >
                <a-button
                  type="text"
                  size="small"
                  @click="handleProducts(record)"
                  >商品管理</a-button
                >
                <a-button type="text" size="small" @click="handleStats(record)"
                  >数据分析</a-button
                >
                <a-dropdown position="br">
                  <a-button type="text" size="small">
                    更多<icon-down />
                  </a-button>
                  <template #content>
                    <a-doption @click="handleCopy(record)">复制活动</a-doption>
                    <a-doption @click="toggleRecommend(record)">
                      {{ record.isRecommend ? "取消推荐" : "设为推荐" }}
                    </a-doption>
                    <a-doption @click="handlePreview(record)"
                      >预览活动</a-doption
                    >
                    <a-doption @click="handleShare(record)">分享活动</a-doption>
                    <a-divider style="margin: 4px 0" />
                    <a-doption
                      @click="handleDelete(record)"
                      style="color: #f53f3f"
                    >
                      删除活动
                    </a-doption>
                  </template>
                </a-dropdown>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 创建/编辑活动弹窗 -->
    <a-modal
      v-model:visible="showModal"
      :title="modalTitle"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form :model="formData" layout="vertical">
        <a-form-item field="name" label="活动名称" required>
          <a-input v-model="formData.name" placeholder="请输入活动名称" />
        </a-form-item>
        <a-form-item field="type" label="活动类型" required>
          <a-select v-model="formData.type" placeholder="请选择活动类型">
            <a-option value="discount">折扣优惠</a-option>
            <a-option value="fullReduction">满减优惠</a-option>
            <a-option value="directReduction">直降优惠</a-option>
            <a-option value="groupBuy">拼团优惠</a-option>
            <a-option value="secondHalf">第二件半价</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="timeRange" label="活动时间" required>
          <a-range-picker v-model="formData.timeRange" show-time />
        </a-form-item>

        <!-- 满减规则 -->
        <template v-if="formData.type === 'fullReduction'">
          <div class="rules-section">
            <div class="rules-header">
              <span>满减规则</span>
              <a-button type="text" @click="addRule">
                <template #icon><icon-plus /></template>
                添加规则
              </a-button>
            </div>
            <div
              v-for="(rule, index) in formData.rules"
              :key="index"
              class="rule-item"
            >
              <span>满</span>
              <a-input-number
                v-model="rule.threshold"
                :min="0"
                :precision="2"
              />
              <span>元减</span>
              <a-input-number v-model="rule.discount" :min="0" :precision="2" />
              <span>元</span>
              <icon-close class="remove-rule" @click="removeRule(index)" />
            </div>
          </div>
        </template>

        <!-- 折扣规则 -->
        <template v-if="formData.type === 'discount'">
          <a-form-item field="discount" label="折扣力度" required>
            <a-input-number
              v-model="formData.discount"
              :min="0"
              :max="10"
              :precision="1"
              :step="0.1"
              style="width: 200px"
            >
              <template #append>折</template>
            </a-input-number>
          </a-form-item>
        </template>

        <!-- 直降规则 -->
        <template v-if="formData.type === 'directReduction'">
          <a-form-item field="reduction" label="直降金额" required>
            <a-input-number
              v-model="formData.reduction"
              :min="0"
              :precision="2"
              style="width: 200px"
            >
              <template #prefix>¥</template>
            </a-input-number>
          </a-form-item>
        </template>

        <!-- 拼团规则 -->
        <template v-if="formData.type === 'groupBuy'">
          <a-form-item field="groupSize" label="成团人数" required>
            <a-input-number v-model="formData.groupSize" :min="2" :max="10" />
          </a-form-item>
          <a-form-item field="groupDiscount" label="拼团折扣" required>
            <a-input-number
              v-model="formData.groupDiscount"
              :min="0"
              :max="10"
              :precision="1"
              :step="0.1"
              style="width: 200px"
            >
              <template #append>折</template>
            </a-input-number>
          </a-form-item>
        </template>

        <a-form-item field="description" label="活动描述">
          <a-textarea
            v-model="formData.description"
            placeholder="请输入活动描述"
            :max-length="200"
            show-word-limit
          />
        </a-form-item>

        <a-form-item field="image" label="活动图片">
          <a-upload
            list-type="picture-card"
            :file-list="formData.imageList"
            @change="handleImageChange"
          >
            <template #upload-button>
              <div>
                <icon-plus />
                <div>上传图片</div>
              </div>
            </template>
          </a-upload>
        </a-form-item>

        <a-form-item field="settings" label="高级设置">
          <a-space direction="vertical" :style="{ width: '100%' }">
            <a-checkbox v-model="formData.settings.limitPerUser">
              每人限购
              <template v-if="formData.settings.limitPerUser">
                <a-input-number
                  v-model="formData.settings.limitQuantity"
                  :min="1"
                  style="width: 100px; margin: 0 8px"
                />
                件
              </template>
            </a-checkbox>
            <a-checkbox v-model="formData.settings.newUserOnly"
              >仅限新用户参与</a-checkbox
            >
            <a-checkbox v-model="formData.settings.memberOnly"
              >仅限会员参与</a-checkbox
            >
          </a-space>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 商品管理弹窗 -->
    <a-modal
      v-model:visible="showProductsModal"
      title="活动商品管理"
      width="800px"
      @ok="handleProductsOk"
      @cancel="handleProductsCancel"
    >
      <div class="products-modal-content">
        <div class="selected-products">
          <div class="section-title">
            <span>已选商品</span>
            <a-button type="primary" size="small" @click="showProductSelector">
              <template #icon><icon-plus /></template>
              添加商品
            </a-button>
          </div>
          <a-table :data="selectedProducts" :pagination="false">
            <template #columns>
              <a-table-column title="商品信息">
                <template #cell="{ record }">
                  <div class="product-info">
                    <a-image :src="record.image" :width="60" />
                    <div class="info-content">
                      <div class="name">{{ record.name }}</div>
                      <div class="price">¥{{ record.price }}</div>
                    </div>
                  </div>
                </template>
              </a-table-column>
              <a-table-column title="活动价" align="center">
                <template #cell="{ record }">
                  <a-input-number
                    v-model="record.promotionPrice"
                    :min="0"
                    :precision="2"
                    style="width: 120px"
                  >
                    <template #prefix>¥</template>
                  </a-input-number>
                </template>
              </a-table-column>
              <a-table-column title="活动库存" align="center">
                <template #cell="{ record }">
                  <a-input-number
                    v-model="record.promotionStock"
                    :min="0"
                    :max="record.stock"
                    style="width: 100px"
                  />
                </template>
              </a-table-column>
              <a-table-column title="操作" align="right">
                <template #cell="{ record }">
                  <a-button
                    type="text"
                    status="danger"
                    @click="removeSelectedProduct(record)"
                  >
                    移除
                  </a-button>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { Message, Modal } from "@arco-design/web-vue";
import {
  IconPlus,
  IconSearch,
  IconRefresh,
  IconDown,
  IconClose,
  IconFire,
  IconGift,
} from "@arco-design/web-vue/es/icon";

// 数据概览
const statistics = reactive({
  activeCount: 8,
  productCount: 156,
  salesAmount: 25680.5,
  conversionRate: 15.8,
});

// 筛选表单
const filterForm = reactive({
  status: "all",
  type: "",
  dateRange: [],
});

// 列表数据
const loading = ref(false);
const promotionList = ref([
  {
    id: 1,
    name: "春季新品大促",
    type: "满减优惠",
    image: "https://example.com/image1.jpg",
    description: "春季新品上市，多买多优惠",
    discountType: "阶梯满减",
    rules: [
      { threshold: 100, discount: 10 },
      { threshold: 200, discount: 30 },
      { threshold: 300, discount: 50 },
    ],
    startTime: "2024-03-01 00:00:00",
    endTime: "2024-03-31 23:59:59",
    status: "进行中",
    productCount: 68,
    salesAmount: 15680.5,
    conversionRate: 12.5,
    isRecommend: true,
  },
  {
    id: 2,
    name: "限时折扣专场",
    type: "折扣优惠",
    image: "https://example.com/image2.jpg",
    description: "全场商品限时8折起",
    discountType: "固定折扣",
    discount: 8,
    startTime: "2024-04-01 00:00:00",
    endTime: "2024-04-15 23:59:59",
    status: "未开始",
    productCount: 45,
    salesAmount: 0,
    conversionRate: 0,
    isRecommend: false,
  },
]);

// 分页配置
const pagination = reactive({
  total: 100,
  current: 1,
  pageSize: 10,
});

// 表单数据
const showModal = ref(false);
const modalTitle = ref("创建活动");
const formData = reactive({
  name: "",
  type: "",
  timeRange: [],
  rules: [],
  discount: 10,
  reduction: 0,
  groupSize: 2,
  groupDiscount: 8,
  description: "",
  imageList: [],
  settings: {
    limitPerUser: false,
    limitQuantity: 1,
    newUserOnly: false,
    memberOnly: false,
  },
});

// 商品管理
const showProductsModal = ref(false);
const selectedProducts = ref([
  {
    id: 1,
    name: "特色桂林米粉",
    image: "https://example.com/product1.jpg",
    price: 15.0,
    promotionPrice: 12.0,
    stock: 1000,
    promotionStock: 500,
  },
]);

// 排序状态
const sortKeys = reactive({
  field: "",
  order: "",
});

// 方法
const getTypeColor = (type) => {
  const colors = {
    满减优惠: "blue",
    折扣优惠: "green",
    直降优惠: "orange",
    拼团优惠: "purple",
    第二件半价: "cyan",
  };
  return colors[type] || "gray";
};

const getStatusColor = (status) => {
  const colors = {
    进行中: "green",
    未开始: "blue",
    已结束: "gray",
  };
  return colors[status] || "gray";
};

const handleSearch = () => {
  loading.value = true;
  // 实现搜索逻辑
  setTimeout(() => {
    loading.value = false;
  }, 1000);
};

const handleReset = () => {
  Object.assign(filterForm, {
    status: "all",
    type: "",
    dateRange: [],
  });
};

const handleCreatePromotion = () => {
  showModal.value = true;
  modalTitle.value = "创建活动";
  Object.assign(formData, {
    name: "",
    type: "",
    timeRange: [],
    rules: [],
    discount: 10,
    reduction: 0,
    groupSize: 2,
    groupDiscount: 8,
    description: "",
    imageList: [],
    settings: {
      limitPerUser: false,
      limitQuantity: 1,
      newUserOnly: false,
      memberOnly: false,
    },
  });
};

const addRule = () => {
  formData.rules.push({
    threshold: 0,
    discount: 0,
  });
};

const removeRule = (index) => {
  formData.rules.splice(index, 1);
};

const handleImageChange = (fileList) => {
  formData.imageList = fileList;
};

const handleEdit = (record) => {
  showModal.value = true;
  modalTitle.value = "编辑活动";
  Object.assign(formData, {
    name: record.name,
    type: record.type,
    timeRange: [record.startTime, record.endTime],
    rules: record.rules || [],
    discount: record.discount || 10,
    reduction: record.reduction || 0,
    description: record.description,
    imageList: record.imageList || [],
  });
};

const handleProducts = (record) => {
  showProductsModal.value = true;
  // 加载活动商品数据
};

const handleStats = (record) => {
  // 实现数据分析逻辑
};

const handleCopy = (record) => {
  // 实现复制活动逻辑
  Message.success("复制成功");
};

const toggleRecommend = (record) => {
  record.isRecommend = !record.isRecommend;
  Message.success(record.isRecommend ? "已设为推荐" : "已取消推荐");
};

const handlePreview = (record) => {
  // 实现预览逻辑
};

const handleShare = (record) => {
  // 实现分享逻辑
};

const handleDelete = (record) => {
  Modal.warning({
    title: "确认删除",
    content: "确定要删除该活动吗？删除后无法恢复。",
    onOk: () => {
      Message.success("删除成功");
    },
  });
};

const handleModalOk = () => {
  // 实现保存逻辑
  showModal.value = false;
  Message.success("保存成功");
};

const handleModalCancel = () => {
  showModal.value = false;
};

const showProductSelector = () => {
  // 实现商品选择器逻辑
};

const removeSelectedProduct = (product) => {
  const index = selectedProducts.value.findIndex((p) => p.id === product.id);
  if (index > -1) {
    selectedProducts.value.splice(index, 1);
  }
};

const handleProductsOk = () => {
  showProductsModal.value = false;
  Message.success("商品设置已保存");
};

const handleProductsCancel = () => {
  showProductsModal.value = false;
};

const onPageChange = (page) => {
  pagination.current = page;
  // 实现分页加载逻辑
};

// 排序处理函数
const handleSort = (field, order) => {
  if (sortKeys.field === field && sortKeys.order === order) {
    // 取消排序
    sortKeys.field = "";
    sortKeys.order = "";
    promotionList.value = [...originalPromotionList];
    Message.success("已取消排序");
    return;
  }

  sortKeys.field = field;
  sortKeys.order = order;

  const sortedList = [...promotionList.value];
  sortedList.sort((a, b) => {
    let compareA = field.includes(".")
      ? field.split(".").reduce((obj, key) => obj[key], a)
      : a[field];
    let compareB = field.includes(".")
      ? field.split(".").reduce((obj, key) => obj[key], b)
      : b[field];

    // 处理特殊字段
    if (field === "salesAmount") {
      compareA = parseFloat(compareA.replace(/,/g, "")) || 0;
      compareB = parseFloat(compareB.replace(/,/g, "")) || 0;
    } else if (field === "startTime" || field === "endTime") {
      compareA = new Date(compareA).getTime();
      compareB = new Date(compareB).getTime();
    }

    if (order === "ascend") {
      return compareA > compareB ? 1 : -1;
    } else {
      return compareA < compareB ? 1 : -1;
    }
  });

  promotionList.value = sortedList;
  Message.success(`${order === "ascend" ? "升序" : "降序"}排序成功`);
};

// 保存原始列表数据
const originalPromotionList = [...promotionList.value];
</script>

<style lang="scss" scoped>
.promotions-page {
  padding: 24px;

  .page-header {
    @apply flex items-center justify-between mb-6;

    .header-left {
      h2 {
        @apply text-xl font-medium m-0;
      }
    }
  }

  .data-overview {
    @apply mb-6;

    .overview-card {
      @apply text-center;
    }
  }

  .filter-card {
    @apply mb-6;
  }

  .list-card {
    .promotion-info {
      @apply flex gap-4;

      .info-content {
        @apply flex-1;

        h4 {
          @apply m-0 mb-2 font-medium;
        }

        .tags {
          @apply mb-2;
        }

        .promotion-desc {
          @apply text-sm text-gray-500;
        }
      }
    }

    .discount-info {
      .discount-type {
        @apply font-medium mb-2;
      }

      .discount-rules {
        @apply text-sm text-gray-600;
      }
    }

    .time-info {
      @apply text-sm text-gray-600;
    }

    .promotion-stats {
      .stat-item {
        @apply flex flex-col items-center mb-2 last:mb-0;

        .label {
          @apply text-sm text-gray-500 mb-1;
        }

        .value {
          @apply font-medium;
        }
      }
    }
  }

  .rules-section {
    @apply mb-4;

    .rules-header {
      @apply flex items-center justify-between mb-2;
    }

    .rule-item {
      @apply flex items-center gap-2 mb-2;

      .remove-rule {
        @apply cursor-pointer text-gray-400 hover:text-red-500;
      }
    }
  }

  .products-modal-content {
    .section-title {
      @apply flex items-center justify-between mb-4;
    }

    .product-info {
      @apply flex items-center gap-4;

      .info-content {
        .name {
          @apply mb-1;
        }

        .price {
          @apply text-sm text-red-500;
        }
      }
    }
  }

  .column-title {
    display: flex;
    align-items: center;
    gap: 8px;

    .sort-buttons {
      display: inline-flex;
      flex-direction: column;
      gap: 2px;
      margin-left: 4px;

      :deep(.arco-icon) {
        font-size: 12px;
        color: var(--color-text-3);
        cursor: pointer;
        line-height: 1;
        padding: 2px;

        &:hover,
        &.active {
          color: rgb(var(--primary-6));
        }
      }
    }
  }
}
</style>
